<template>
  <div class="file-history-container">
    <h1 class="page-title">文件历史</h1>
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    <div v-else-if="error" class="error-container">
      <el-alert
        :title="error"
        type="error"
        show-icon
      />
    </div>
    <div v-else class="history-content">
      <el-card class="filter-card">
        <el-form :inline="true" :model="filters" class="filter-form">
          <el-form-item label="项目">
            <el-select v-model="filters.project" placeholder="选择项目" clearable>
              <el-option
                v-for="item in projectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="文件类型">
            <el-select v-model="filters.fileType" placeholder="选择文件类型" clearable>
              <el-option label="文档" value="document" />
              <el-option label="图片" value="image" />
              <el-option label="代码" value="code" />
              <el-option label="其他" value="other" />
            </el-select>
          </el-form-item>
          <el-form-item label="操作类型">
            <el-select v-model="filters.actionType" placeholder="选择操作类型" clearable>
              <el-option label="上传" value="upload" />
              <el-option label="下载" value="download" />
              <el-option label="修改" value="edit" />
              <el-option label="删除" value="delete" />
              <el-option label="查看" value="view" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="filters.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchFiles">搜索</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <div class="file-timeline">
        <el-timeline>
          <el-timeline-item
            v-for="(day, dayIndex) in groupedHistory"
            :key="dayIndex"
            :timestamp="day.date"
            placement="top"
            :type="'primary'"
            size="large"
          >
            <el-card class="day-card">
              <div class="day-summary">
                <div>操作次数: <strong>{{ day.items.length }}</strong></div>
                <div>主要操作人: <strong>{{ getMostActiveUser(day.items) }}</strong></div>
              </div>
              <el-timeline>
                <el-timeline-item
                  v-for="(record, recordIndex) in day.items"
                  :key="recordIndex"
                  :timestamp="formatTime(record.timestamp)"
                  :type="getActionTypeColor(record.actionType)"
                >
                  <div class="history-record">
                    <div class="record-header">
                      <span class="file-name">{{ record.fileName }}</span>
                      <el-tag size="small" :type="getFileTypeColor(record.fileType)">
                        {{ getFileTypeText(record.fileType) }}
                      </el-tag>
                      <el-tag size="small" :type="getActionTypeColor(record.actionType)">
                        {{ getActionTypeText(record.actionType) }}
                      </el-tag>
                    </div>
                    <div class="record-info">
                      <span class="info-item">
                        <strong>项目:</strong> {{ record.project }}
                      </span>
                      <span class="info-item">
                        <strong>大小:</strong> {{ formatFileSize(record.fileSize) }}
                      </span>
                      <span class="info-item">
                        <strong>用户:</strong> {{ record.user }}
                      </span>
                    </div>
                    <div class="record-description" v-if="record.description">
                      {{ record.description }}
                    </div>
                    <div class="record-actions">
                      <el-button
                        v-if="record.fileType !== 'delete'"
                        type="primary"
                        size="small"
                        @click="viewFile(record)"
                      >
                        查看
                      </el-button>
                      <el-button
                        v-if="record.fileType !== 'delete'"
                        type="success"
                        size="small"
                        @click="downloadFile(record)"
                      >
                        下载
                      </el-button>
                      <el-button
                        v-if="record.actionType === 'edit' && record.previousVersions && record.previousVersions.length > 0"
                        type="warning"
                        size="small"
                        @click="showVersionHistory(record)"
                      >
                        版本历史
                      </el-button>
                    </div>
                  </div>
                </el-timeline-item>
              </el-timeline>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </div>

    <!-- 文件预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      :title="currentFile.fileName"
      width="70%"
      destroy-on-close
    >
      <div class="file-preview">
        <div v-if="currentFile.fileType === 'image'" class="image-preview">
          <img :src="currentFile.url" alt="Preview" style="max-width: 100%;" />
        </div>
        <div v-else-if="currentFile.fileType === 'document'" class="document-preview">
          <iframe :src="currentFile.url" style="width: 100%; height: 600px;"></iframe>
        </div>
        <div v-else-if="currentFile.fileType === 'code'" class="code-preview">
          <pre>{{ currentFile.content }}</pre>
        </div>
        <div v-else class="unavailable-preview">
          <p>无法预览此类型文件，请下载后查看。</p>
        </div>
      </div>
    </el-dialog>

    <!-- 版本历史对话框 -->
    <el-dialog
      v-model="versionDialogVisible"
      title="文件版本历史"
      width="70%"
    >
      <div class="version-history" v-if="currentFile.previousVersions">
        <el-table :data="currentFile.previousVersions" style="width: 100%">
          <el-table-column prop="version" label="版本" width="100" />
          <el-table-column prop="timestamp" label="时间">
            <template #default="scope">
              {{ formatDateTime(scope.row.timestamp) }}
            </template>
          </el-table-column>
          <el-table-column prop="user" label="操作人" width="120" />
          <el-table-column prop="description" label="变更描述" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button type="primary" size="small" @click="viewVersionFile(scope.row)">查看</el-button>
              <el-button type="success" size="small" @click="downloadVersionFile(scope.row)">下载</el-button>
              <el-button 
                v-if="scope.row.version !== currentFile.previousVersions[currentFile.previousVersions.length - 1].version" 
                type="warning" 
                size="small" 
                @click="compareVersions(currentFile.previousVersions[currentFile.previousVersions.length - 1], scope.row)"
              >
                对比
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'FileHistory',
  setup() {
    const fileHistory = ref([])
    const loading = ref(true)
    const error = ref(null)
    const previewDialogVisible = ref(false)
    const versionDialogVisible = ref(false)
    const currentFile = ref({})
    
    const filters = reactive({
      project: '',
      fileType: '',
      actionType: '',
      dateRange: []
    })
    
    const projectOptions = ref([
      { value: '前端重构', label: '前端重构' },
      { value: '后端优化', label: '后端优化' },
      { value: '数据分析平台', label: '数据分析平台' },
      { value: '移动应用开发', label: '移动应用开发' }
    ])
    
    const fetchFileHistory = async () => {
      try {
        loading.value = true
        // 这里替换为实际的 API 调用
        // const response = await fetch('/api/files/history')
        // fileHistory.value = await response.json()
        
        // 模拟数据
        setTimeout(() => {
          fileHistory.value = [
            {
              id: 'F-1001',
              fileName: '需求分析文档.docx',
              fileType: 'document',
              fileSize: 2500000,
              project: '前端重构',
              actionType: 'upload',
              user: '张三',
              timestamp: '2024-05-15T09:30:00',
              description: '上传了项目需求分析文档初稿',
              url: '#'
            },
            {
              id: 'F-1002',
              fileName: '界面设计稿.png',
              fileType: 'image',
              fileSize: 4300000,
              project: '前端重构',
              actionType: 'edit',
              user: '李四',
              timestamp: '2024-05-15T11:45:00',
              description: '更新了首页界面设计',
              url: '#',
              previousVersions: [
                { version: 'v1', timestamp: '2024-05-14T10:20:00', user: '李四', description: '初始版本', url: '#' },
                { version: 'v2', timestamp: '2024-05-14T16:30:00', user: '李四', description: '调整了色彩方案', url: '#' },
                { version: 'v3', timestamp: '2024-05-15T11:45:00', user: '李四', description: '更新了布局', url: '#' }
              ]
            },
            {
              id: 'F-1003',
              fileName: 'AppHeader.vue',
              fileType: 'code',
              fileSize: 15000,
              project: '前端重构',
              actionType: 'edit',
              user: '王五',
              timestamp: '2024-05-15T14:20:00',
              description: '修复了响应式布局问题',
              url: '#',
              content: `<template>
  <header class="app-header">
    <div class="logo">
      <img src="@/assets/logo.png" alt="Logo">
      <h1>任务管理系统</h1>
    </div>
    <nav class="navigation">
      <!-- 导航菜单 -->
    </nav>
  </header>
</template>`,
              previousVersions: [
                { version: 'v1', timestamp: '2024-05-10T09:15:00', user: '王五', description: '创建组件', url: '#' },
                { version: 'v2', timestamp: '2024-05-15T14:20:00', user: '王五', description: '修复响应式问题', url: '#' }
              ]
            },
            {
              id: 'F-1004',
              fileName: '项目计划.xlsx',
              fileType: 'document',
              fileSize: 1800000,
              project: '数据分析平台',
              actionType: 'download',
              user: '赵六',
              timestamp: '2024-05-15T16:10:00',
              description: '下载了项目计划文档进行审阅',
              url: '#'
            },
            {
              id: 'F-1005',
              fileName: '旧版API文档.md',
              fileType: 'document',
              fileSize: 500000,
              project: '后端优化',
              actionType: 'delete',
              user: '钱七',
              timestamp: '2024-05-15T17:30:00',
              description: '删除了过时的API文档'
            },
            {
              id: 'F-1006',
              fileName: '数据模型设计.pdf',
              fileType: 'document',
              fileSize: 3200000,
              project: '数据分析平台',
              actionType: 'view',
              user: '张三',
              timestamp: '2024-05-16T09:15:00',
              description: '查看了数据模型设计文档',
              url: '#'
            },
            {
              id: 'F-1007',
              fileName: 'DashboardChart.js',
              fileType: 'code',
              fileSize: 25000,
              project: '数据分析平台',
              actionType: 'edit',
              user: '李四',
              timestamp: '2024-05-16T10:45:00',
              description: '优化了图表渲染性能',
              url: '#',
              content: `// 图表配置
const chartConfig = {
  type: 'line',
  data: {
    labels: ['一月', '二月', '三月', '四月', '五月', '六月'],
    datasets: [{
      label: '任务完成数',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: 'rgba(75, 192, 192, 0.2)',
      borderColor: 'rgba(75, 192, 192, 1)',
      borderWidth: 1
    }]
  },
  options: {
    responsive: true,
    maintainAspectRatio: false
  }
};`,
              previousVersions: [
                { version: 'v1', timestamp: '2024-05-12T14:30:00', user: '李四', description: '创建图表组件', url: '#' },
                { version: 'v2', timestamp: '2024-05-16T10:45:00', user: '李四', description: '性能优化', url: '#' }
              ]
            },
            {
              id: 'F-1008',
              fileName: '移动端原型.sketch',
              fileType: 'other',
              fileSize: 8500000,
              project: '移动应用开发',
              actionType: 'upload',
              user: '王五',
              timestamp: '2024-05-16T13:20:00',
              description: '上传了移动应用原型设计文件',
              url: '#'
            }
          ]
          loading.value = false
        }, 1000)
      } catch (err) {
        error.value = '获取文件历史记录失败'
        loading.value = false
        console.error(err)
      }
    }
    
    // 根据过滤条件过滤文件历史
    const filteredHistory = computed(() => {
      return fileHistory.value.filter(record => {
        const projectMatch = !filters.project || record.project === filters.project
        const fileTypeMatch = !filters.fileType || record.fileType === filters.fileType
        const actionTypeMatch = !filters.actionType || record.actionType === filters.actionType
        
        let dateMatch = true
        if (filters.dateRange && filters.dateRange.length === 2) {
          const recordDate = new Date(record.timestamp.split('T')[0])
          const startDate = new Date(filters.dateRange[0])
          const endDate = new Date(filters.dateRange[1])
          
          dateMatch = recordDate >= startDate && recordDate <= endDate
        }
        
        return projectMatch && fileTypeMatch && actionTypeMatch && dateMatch
      })
    })
    
    // 将文件历史按日期分组
    const groupedHistory = computed(() => {
      const groups = {}
      
      filteredHistory.value.forEach(record => {
        const date = record.timestamp.split('T')[0]
        
        if (!groups[date]) {
          groups[date] = {
            date: formatDate(date),
            items: []
          }
        }
        
        groups[date].items.push(record)
      })
      
      // 转换为数组并按日期排序（最新的在前）
      return Object.values(groups).sort((a, b) => {
        return new Date(b.date) - new Date(a.date)
      })
    })
    
    const formatDate = (dateString) => {
      if (!dateString) return '-'
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN')
    }
    
    const formatTime = (dateTimeString) => {
      if (!dateTimeString) return '-'
      const date = new Date(dateTimeString)
      return date.toLocaleTimeString('zh-CN')
    }
    
    const formatDateTime = (dateTimeString) => {
      if (!dateTimeString) return '-'
      const date = new Date(dateTimeString)
      return date.toLocaleString('zh-CN')
    }
    
    const formatFileSize = (bytes) => {
      if (bytes === 0) return '0 B'
      
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }
    
    const getFileTypeText = (type) => {
      switch (type) {
        case 'document':
          return '文档'
        case 'image':
          return '图片'
        case 'code':
          return '代码'
        case 'other':
          return '其他'
        default:
          return '未知'
      }
    }
    
    const getFileTypeColor = (type) => {
      switch (type) {
        case 'document':
          return 'primary'
        case 'image':
          return 'success'
        case 'code':
          return 'warning'
        case 'other':
          return 'info'
        default:
          return 'info'
      }
    }
    
    const getActionTypeText = (type) => {
      switch (type) {
        case 'upload':
          return '上传'
        case 'download':
          return '下载'
        case 'edit':
          return '修改'
        case 'delete':
          return '删除'
        case 'view':
          return '查看'
        default:
          return '未知'
      }
    }
    
    const getActionTypeColor = (type) => {
      switch (type) {
        case 'upload':
          return 'success'
        case 'download':
          return 'info'
        case 'edit':
          return 'warning'
        case 'delete':
          return 'danger'
        case 'view':
          return 'info'
        default:
          return 'info'
      }
    }
    
    const getMostActiveUser = (items) => {
      const userCounts = {}
      
      items.forEach(item => {
        if (!userCounts[item.user]) {
          userCounts[item.user] = 0
        }
        userCounts[item.user]++
      })
      
      let mostActiveUser = ''
      let maxCount = 0
      
      for (const user in userCounts) {
        if (userCounts[user] > maxCount) {
          mostActiveUser = user
          maxCount = userCounts[user]
        }
      }
      
      return mostActiveUser
    }
    
    const searchFiles = () => {
      // 实际应用中可能需要调用API进行搜索
      // 这里直接使用计算属性filteredHistory
      if (filteredHistory.value.length === 0) {
        ElMessage.warning('没有找到符合条件的文件记录')
      }
    }
    
    const resetFilters = () => {
      filters.project = ''
      filters.fileType = ''
      filters.actionType = ''
      filters.dateRange = []
    }
    
    const viewFile = (file) => {
      currentFile.value = file
      previewDialogVisible.value = true
    }
    
    const downloadFile = (file) => {
      // 实际应用中应该下载文件
      ElMessage.success(`开始下载文件: ${file.fileName}`)
    }
    
    const showVersionHistory = (file) => {
      currentFile.value = file
      versionDialogVisible.value = true
    }
    
    const viewVersionFile = (version) => {
      // 实际应用中应该查看特定版本的文件
      ElMessage.info(`查看文件版本: ${version.version}`)
    }
    
    const downloadVersionFile = (version) => {
      // 实际应用中应该下载特定版本的文件
      ElMessage.success(`开始下载文件版本: ${version.version}`)
    }
    
    const compareVersions = (version1, version2) => {
      // 实际应用中应该比较两个版本
      ElMessage.info(`比较版本: ${version1.version} 和 ${version2.version}`)
    }
    
    onMounted(() => {
      fetchFileHistory()
    })
    
    return {
      fileHistory,
      loading,
      error,
      filters,
      projectOptions,
      filteredHistory,
      groupedHistory,
      previewDialogVisible,
      versionDialogVisible,
      currentFile,
      formatDate,
      formatTime,
      formatDateTime,
      formatFileSize,
      getFileTypeText,
      getFileTypeColor,
      getActionTypeText,
      getActionTypeColor,
      getMostActiveUser,
      searchFiles,
      resetFilters,
      viewFile,
      downloadFile,
      showVersionHistory,
      viewVersionFile,
      downloadVersionFile,
      compareVersions
    }
  }
}
</script>

<style scoped>
.file-history-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.file-timeline {
  margin-top: 30px;
}

.day-card {
  margin-bottom: 15px;
}

.day-summary {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  font-size: 14px;
  color: #606266;
}

.history-record {
  padding: 10px;
  border-radius: 4px;
  background-color: #f8f8f8;
  margin-bottom: 10px;
}

.record-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.file-name {
  font-weight: bold;
  margin-right: 10px;
  font-size: 16px;
}

.record-info {
  margin-bottom: 10px;
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #606266;
}

.record-description {
  margin-bottom: 10px;
  padding: 5px 0;
  color: #606266;
  font-size: 14px;
}

.record-actions {
  display: flex;
  gap: 10px;
}

.code-preview {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 15px;
  max-height: 600px;
  overflow: auto;
}

.code-preview pre {
  margin: 0;
  font-family: 'Courier New', Courier, monospace;
  white-space: pre-wrap;
}

.unavailable-preview {
  text-align: center;
  padding: 50px;
  color: #909399;
}

.loading-container,
.error-container {
  margin: 30px 0;
}
</style> 